using Microsoft.AspNetCore.Mvc;
using WebAPI.Dao;
using WebAPI.Entities;
using WebAPI.Entities.Dto;
using WebAPI.Services;

namespace WebAPI.Controllers;

[ApiController]
[Route("api/[controller]/[Action]")]
public class UserController : ControllerBase
{
    private UserService _userService = new UserService();
    
    [HttpPost(Name = "UserLogin")]
    public string UserLogin(UserLoginDto userLoginDto)
    {
        User user = _userService.Login(userLoginDto.Username, userLoginDto.Password);
        if (user == null)
        {
            return ResultData.UsernameOrPasswordWrong("用户名或密码错误");
        }

        user.Password = JwtHelper.SetJwtEncode(userLoginDto.Username);
        
        return ResultData.Ok(user);
    }
    
    [HttpGet(Name = "GetUser")]
    public ActionResult<User> GetUser(string username)
    {
        User user = _userService.GetOne(username);
        if (user == null)
        {
            return NotFound("用户不存在!");
        }
        return Ok(user);
    }
    
    [HttpPut(Name = "UserRegister")]
    public ActionResult<User> UserRegister(UserRegisterDto userRegisterDto)
    {
        User user = new User();
        user.Ip = userRegisterDto.Ip;
        Console.WriteLine(user.Ip);
        user.Username = userRegisterDto.Username;
        user.Password = userRegisterDto.Password;
        user.PhoneNumber = userRegisterDto.PhoneNumber;
        if (_userService.Register(user))
        {
            return Ok("注册成功");
        }

        return BadRequest("注册失败");
    }
    
    [HttpPut(Name = "UserDelete")]
    public bool UserDelete(string id)
    {
        User user = new User();
        user.Id = id;
        return _userService.DeleteUser(user);
    }
    
    [HttpPut(Name = "UserLogout")]
    public bool UserLogout(UserLoginDto userLoginDto)
    {
        try
        {
            userLoginDto.Password = "";
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
        
        return true;
    }
}